package com.lx.preferred.mall.authcenter.service;

import com.lx.mall.common.api.CommonResult;
import com.lx.preferred.mall.authcenter.domain.MemberDetails;
import com.lx.preferred.mall.authcenter.feign.UmsMemberFeignService;
import com.lx.preferred.mall.authcenter.model.UmsMember;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;


/**
 * @author lX
 * @version JDK 8
 * @className PreferredUserDetailService (此处以class为例)
 * @date 2024/12/12
 * @description TODO
 */
@Component
public class PreferredUserDetailService  implements UserDetailsService {

  Logger logger = LoggerFactory.getLogger(PreferredUserDetailService.class);


  @Autowired
  private UmsMemberFeignService umsMemberFeignService;
  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    // 加载用户信息
    if(StringUtils.isEmpty(username)) {
      logger.warn("用户登陆用户名为空:{}",username);
      throw new UsernameNotFoundException("用户名不能为空");
    }

    UmsMember umsMember = getByUsername(username);
    if(null == umsMember) {
      throw new UsernameNotFoundException("根据用户名没有查询到对应的用户信息");
    }

    logger.info("根据用户名:{}获取用户登陆信息:{}",username,umsMember);

    // 会员信息的封装 implements UserDetails
    MemberDetails memberDetails = new MemberDetails(umsMember);

    return memberDetails;

  }


  /**
   * 根据用户名查询用户信息
   * @param username
   * @return
   */
  public UmsMember getByUsername(String username) {
    // fegin获取会员信息
    CommonResult<UmsMember> umsMemberCommonResult = umsMemberFeignService.loadUserByUsername(username);

    return umsMemberCommonResult.getData();
  }
}
